<script lang="ts">
	import type { PlanInfo, PlanItemInfo } from '$lib/api/proto/roadmap_plan_api';
	import { USER_ROLE } from '$lib/api/proto/user_api';
	import { userStore } from '$lib/stores/user.svelte';
	import { EllipsisVertical } from 'lucide-svelte';
	import moment from 'moment';
	import EditPlanModal from './EditPlanModal.svelte';
	import SimpleEditor from '$lib/components/editor/SimpleEditor.svelte';
	import { Calendar, DayGrid, Interaction, TimeGrid } from '@event-calendar/core';
	import ConfirmModal from '$lib/components/modal/ConfirmModal.svelte';
	import EditPlanItemModal from './EditPlanItemModal.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { appStore } from '$lib/stores/app.svelte';
	import ViewPlanItemModal from './ViewPlanItemModal.svelte';

	interface Props {
		roadmapId: string;
		plan: PlanInfo;
		onChange: () => void;
		onRemove: () => void;
	}
	let props: Props = $props();

	let showUpdateModal = $state(false);
	let showRemoveModal = $state(false);

	let clickDateInfo = $state(null as Calendar.DateClickInfo | null);

	let planItemList = $state([] as PlanItemInfo[]);

	let clickPlanItem = $state(null as PlanItemInfo | null);

	const eventList: Calendar.Event[] = $derived(
		planItemList.map((item) => ({
			id: item.itemId,
			start: new Date(Number(item.basicInfo?.startTime ?? 0)),
			end: new Date(Number(item.basicInfo?.endTime ?? 0)),
			resourceIds: [],
			allDay: false,
			title: item.basicInfo?.title ?? '',
			editable: userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH,
			startEditable: userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH,
			durationEditable: userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH,
			display: 'auto',
			backgroundColor: 'var(--color-primary)',
			textColor: 'var(--color-primary-content)',
			classNames: [],
			styles: ['cursor: pointer;'],
			extendedProps: {}
		}))
	);

	async function loadPlanItemList() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.roadmapPlanApiClient.listPlanItem({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				targetMemberUserId: props.plan.memberUserId,
				planId: props.plan.planId
			}).response
		);
		planItemList = res.itemList;
	}

	async function onUpdatePlanItem(itemId: string) {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.roadmapPlanApiClient.getPlanItem({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				targetMemberUserId: props.plan.memberUserId,
				planId: props.plan.planId,
				itemId: itemId
			}).response
		);
		if (res.item == undefined) {
			return;
		}

		const tmpList = planItemList.slice();
		const index = tmpList.findIndex((item) => item.itemId == itemId);
		if (index == -1) {
			tmpList.push(res.item);
		} else {
			tmpList[index] = res.item;
		}
		planItemList = tmpList;
	}

	async function onItemDrop(info: Calendar.EventDropInfo) {
		if (userStore.userSession == null) {
			return;
		}
		const tmpList = planItemList.slice();
		const index = tmpList.findIndex((item) => item.itemId == info.event.id);
		if (index == -1) {
			planItemList = tmpList;
			return;
		}
		const planItem = tmpList[index];
		if (planItem.basicInfo == undefined) {
			return;
		}
		await callApi(
			appStore.roadmapPlanApiClient.updatePlanItem({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				targetMemberUserId: props.plan.memberUserId,
				planId: props.plan.planId,
				itemId: info.event.id as string,
				basicInfo: {
					title: planItem.basicInfo.title,
					content: planItem.basicInfo.content,
					startTime: BigInt(info.event.start.valueOf()),
					endTime: BigInt(info.event.end.valueOf())
				}
			}).response
		);
		planItem.basicInfo.startTime = BigInt(info.event.start.valueOf());
		planItem.basicInfo.endTime = BigInt(info.event.end.valueOf());
		tmpList[index] = planItem;
		planItemList = tmpList;
	}

	async function onItemResize(info: Calendar.EventResizeInfo) {
		if (userStore.userSession == null) {
			return;
		}
		const tmpList = planItemList.slice();
		const index = tmpList.findIndex((item) => item.itemId == info.event.id);
		if (index == -1) {
			planItemList = tmpList;
			return;
		}
		const planItem = tmpList[index];
		if (planItem.basicInfo == undefined) {
			return;
		}

		const newEndTime = moment(Number(planItem.basicInfo.endTime))
			.add(info.endDelta.seconds, 'seconds')
			.valueOf();

		await callApi(
			appStore.roadmapPlanApiClient.updatePlanItem({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				targetMemberUserId: props.plan.memberUserId,
				planId: props.plan.planId,
				itemId: info.event.id as string,
				basicInfo: {
					title: planItem.basicInfo.title,
					content: planItem.basicInfo.content,
					startTime: planItem.basicInfo.startTime,
					endTime: BigInt(newEndTime)
				}
			}).response
		);
		planItem.basicInfo.endTime = BigInt(newEndTime);
		tmpList[index] = planItem;
		planItemList = tmpList;
	}

	$effect(() => {
		loadPlanItemList();
	});
</script>

<div class="h-[calc(100vh-170px)] overflow-y-auto w-full">
	<div class="flex justify-between">
		<h3 class="text-xl">{props.plan.basicInfo?.planName}</h3>
		<div class="flex gap-2 items-center">
			<span
				>{moment(Number(props.plan.startTime)).format('YYYY-MM-DD')} - {moment(
					Number(props.plan.endTime)
				).format('YYYY-MM-DD')}</span
			>
			{#if userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH}
				<div class="dropdown">
					<div tabindex="0" role="button" class="btn btn-ghost">
						<EllipsisVertical size={16} />
					</div>
					<ul
						class="menu dropdown-content bg-base-100 rounded-box z-1 w-[80px] p-2 shadow-sm gap-2"
					>
						<li>
							<button type="button" class="btn btn-ghost" onclick={() => (showUpdateModal = true)}
								>修改</button
							>
						</li>
						<li class="text-error">
							<button type="button" class="btn btn-ghost" onclick={() => (showRemoveModal = true)}
								>删除</button
							>
						</li>
					</ul>
				</div>
			{/if}
		</div>
	</div>
	<div class="divider m-0"></div>
	<SimpleEditor sizeClass="" readOnly data={props.plan.basicInfo?.planDesc} />
	<div class="p-2">
		<Calendar
			plugins={[TimeGrid,DayGrid, Interaction]}
			options={{
				allDaySlot: false,
				buttonText: {
					dayGridMonth: '月',
					timeGridWeek: '周'
				},
				dateClick: (info) => {
					if (userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH) {
						clickDateInfo = info;
					}
				},
				eventClick: (info) => {
					const planItem = planItemList.find((item) => item.itemId == info.event.id);
					if (planItem != undefined) {
						clickPlanItem = planItem;
					}
				},
				eventDrop: (info) => {
					if (userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH) {
						onItemDrop(info);
					}
				},
				eventResize: (info) => {
					if (userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH) {
						onItemResize(info);
					}
				},
				editable: userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH,
				events: eventList,
				firstDay: 1,
				headerToolbar: {
					start: '',
					center: '',
					end: 'dayGridMonth timeGridWeek  prev,next'
				},
				validRange: {
					start: new Date(Number(props.plan.startTime)),
					end: new Date(Number(props.plan.endTime))
				}
			}}
		/>
	</div>
</div>

<div class="absolute -left-[10000px]">
	{#if showUpdateModal}
		<EditPlanModal
			plan={props.plan}
			roadmapId={props.roadmapId}
			memberUserId={props.plan.memberUserId}
			onCancel={() => (showRemoveModal = false)}
			onOk={() => {
				showUpdateModal = false;
				props.onChange();
			}}
		/>
	{/if}
	{#if showRemoveModal}
		<ConfirmModal
			title="删除成长计划"
			content="是否删除成长计划 {props.plan.basicInfo?.planName} ?"
			okName="删除"
			type="error"
			onCancel={() => (showRemoveModal = false)}
			onOk={() => {
				showRemoveModal = false;
				props.onRemove();
			}}
		/>
	{/if}
	{#if clickDateInfo != null}
		<EditPlanItemModal
			roadmapId={props.roadmapId}
			plan={props.plan}
			{clickDateInfo}
			onCancel={() => (clickDateInfo = null)}
			onOk={(itemId) => {
				clickDateInfo = null;
				onUpdatePlanItem(itemId);
			}}
		/>
	{/if}
	{#if clickPlanItem != null}
		{#if userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_COACH}
			<EditPlanItemModal
				roadmapId={props.roadmapId}
				plan={props.plan}
				planItem={clickPlanItem}
				onCancel={() => (clickPlanItem = null)}
				onOk={(itemId) => {
					clickPlanItem = null;
					onUpdatePlanItem(itemId);
				}}
			/>
		{:else if userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_STUDENT}
			<ViewPlanItemModal planItem={clickPlanItem} onClose={() => (clickPlanItem = null)} />
		{/if}
	{/if}
</div>
